import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../shared/utils/responsive_utils.dart';

import '../../features/dashboard/view/dashboard_page.dart';
import '../../features/capture/view/capture_page.dart';
import '../../features/profile/view/profile_page.dart';
import '../../features/profile/view/profile_edit_page.dart';
import '../../features/onboarding/view/onboarding_page.dart';
import '../../features/profile_setup/view/profile_setup_page.dart';
import '../../features/explain/view/explain_page.dart';
import '../../features/mistakes/view/mistakes_page.dart';
import '../../features/auth/view/login_page.dart';
import '../../features/auth/view/unauthorized_page.dart';
import '../../features/h5/view/h5_page.dart';
import '../../features/splash/view/splash_page.dart';
import '../../features/curriculum/view/curriculum_page.dart';
import '../../features/curriculum/view/knowledge_points_page.dart';
import '../../features/capture/view/chat_history_page.dart';
import '../../features/capture/view/chat_history_detail_page.dart';

final Provider<GoRouter> goRouterProvider = Provider<GoRouter>((ref) {
  return GoRouter(
    initialLocation: '/splash',
    redirect: (context, state) {
      // 如果访问根路径，重定向到启动页
      if (state.uri.path == '/') {
        return '/splash';
      }
      return null;
    },
    routes: <RouteBase>[
      GoRoute(
        path: '/splash',
        builder:
            (BuildContext context, GoRouterState state) => const SplashPage(),
      ),
      GoRoute(
        path: '/onboarding',
        builder:
            (BuildContext context, GoRouterState state) =>
                const OnboardingPage(),
      ),
      GoRoute(
        path: '/login',
        builder:
            (BuildContext context, GoRouterState state) => const LoginPage(),
      ),
      GoRoute(
        path: '/profile-setup',
        builder:
            (BuildContext context, GoRouterState state) =>
                const ProfileSetupPage(),
      ),
      ShellRoute(
        builder: (context, state, child) => _ScaffoldWithNavBar(child: child),
        routes: <RouteBase>[
          GoRoute(
            path: '/dashboard',
            builder:
                (BuildContext context, GoRouterState state) =>
                    const DashboardPage(),
          ),
          GoRoute(
            path: '/capture',
            builder:
                (BuildContext context, GoRouterState state) =>
                    const CapturePage(),
          ),
          GoRoute(
            path: '/profile',
            builder:
                (BuildContext context, GoRouterState state) =>
                    const ProfilePage(),
          ),
        ],
      ),
      // 独立页面（不在底部导航栏中）
      GoRoute(
        path: '/explain',
        builder:
            (BuildContext context, GoRouterState state) => const ExplainPage(),
      ),
      // AI历史记录
      GoRoute(
        path: '/ai/history',
        builder:
            (BuildContext context, GoRouterState state) =>
                const ChatHistoryPage(),
      ),
      GoRoute(
        path: '/ai/history/:conversationId',
        builder: (BuildContext context, GoRouterState state) {
          final id = state.pathParameters['conversationId']!;
          return ChatHistoryDetailPage(conversationId: id);
        },
      ),
      GoRoute(
        path: '/mistakes',
        builder:
            (BuildContext context, GoRouterState state) => const MistakesPage(),
      ),
      GoRoute(
        path: '/h5',
        builder: (BuildContext context, GoRouterState state) => const H5Page(),
      ),
      GoRoute(
        path: '/profile-edit',
        builder:
            (BuildContext context, GoRouterState state) =>
                const ProfileEditPage(),
      ),
      GoRoute(
        path: '/unauthorized',
        builder:
            (BuildContext context, GoRouterState state) =>
                const UnauthorizedPage(),
      ),
      // 教材大纲页面
      GoRoute(
        path: '/curriculum',
        builder:
            (BuildContext context, GoRouterState state) =>
                const CurriculumPage(),
      ),
      // 知识点详情页面
      GoRoute(
        path: '/curriculum/:chapterId',
        builder: (BuildContext context, GoRouterState state) {
          final chapterId = state.pathParameters['chapterId']!;
          final chapterTitle = state.uri.queryParameters['title'] ?? '章节详情';
          return KnowledgePointsPage(
            chapterId: chapterId,
            chapterTitle: chapterTitle,
          );
        },
      ),
    ],
  );
});

class _ScaffoldWithNavBar extends StatelessWidget {
  const _ScaffoldWithNavBar({required this.child});
  final Widget child;

  @override
  Widget build(BuildContext context) {
    final ColorScheme cs = Theme.of(context).colorScheme;
    return Scaffold(
      body: child,
      bottomNavigationBar: Container(
        decoration: BoxDecoration(
          color: cs.surface,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.06),
              blurRadius: 12,
              offset: const Offset(0, -2),
            ),
          ],
        ),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(
              horizontal: ResponsiveUtils.getResponsiveSpacing(context, 12),
              vertical: ResponsiveUtils.getResponsiveSpacing(context, 10),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                _NavBarItem(
                  icon: Icons.home_outlined,
                  selectedIcon: Icons.home_rounded,
                  label: '主页',
                  isSelected: _calculateSelectedIndex(context) == 0,
                  onTap: () => context.go('/dashboard'),
                ),
                _NavBarItem(
                  icon: Icons.smart_toy_outlined,
                  selectedIcon: Icons.smart_toy_rounded,
                  label: 'AI助手',
                  isSelected: _calculateSelectedIndex(context) == 1,
                  onTap: () => context.go('/capture'),
                ),
                _NavBarItem(
                  icon: Icons.person_outline_rounded,
                  selectedIcon: Icons.person_rounded,
                  label: '我的',
                  isSelected: _calculateSelectedIndex(context) == 2,
                  onTap: () => context.go('/profile'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  int _calculateSelectedIndex(BuildContext context) {
    final String location = GoRouterState.of(context).uri.path;
    switch (location) {
      case '/dashboard':
        return 0;
      case '/capture':
        return 1;
      case '/profile':
        return 2;
      default:
        return 0;
    }
  }
}

class _NavBarItem extends StatelessWidget {
  const _NavBarItem({
    required this.icon,
    required this.selectedIcon,
    required this.label,
    required this.isSelected,
    required this.onTap,
  });

  final IconData icon;
  final IconData selectedIcon;
  final String label;
  final bool isSelected;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final ColorScheme cs = Theme.of(context).colorScheme;
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 180),
        padding: EdgeInsets.symmetric(
          horizontal: ResponsiveUtils.getResponsiveSpacing(context, 18),
          vertical: ResponsiveUtils.getResponsiveSpacing(context, 10),
        ),
        decoration: BoxDecoration(
          color: isSelected ? cs.primaryContainer : Colors.transparent,
          borderRadius: BorderRadius.circular(
            ResponsiveUtils.getResponsiveRadius(context, 24),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Icon(
              isSelected ? selectedIcon : icon,
              color: isSelected ? cs.primary : cs.onSurface.withOpacity(0.7),
              size: ResponsiveUtils.getResponsiveIconSize(context, 26),
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 6)),
            Text(
              label,
              style: TextStyle(
                fontSize: ResponsiveUtils.getResponsiveFontSize(context, 13),
                fontWeight: isSelected ? FontWeight.w700 : FontWeight.w500,
                color: isSelected ? cs.primary : cs.onSurface.withOpacity(0.7),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
